/* The N3 documentation block starts here. Please leave this line untouched. <N3
#
# This is an N3 documentation block for xOperator query scripts. This means,
# after the starting <N3 and before the ending N3> Notation3 is spoken. You
# must not set the rdf: rdfs: owl: dc: and xop: prefixes in this block
# because they are predefined with the common used namespaces. The prefix xop:
# represents http://ns.aksw.org/xop/ which is the xOperator vocabulary.

# Use only your registered script URL here - other subjects will be ignored!
<https://xoperator.googlecode.com/svn/branches/xoperatormvc/conf/example_at_example.com/aiml/templates/iCalWhereNow.groovy> a xop:QueryScript;
	rdfs:label "iCalWhereNow";
	rdfs:comment "Query RDF iCal calendar which are linked to your buddies.";
	dc:creator "Sebastian Dietzold";
	xop:aimlPattern "WHERE IS * NOW".

# This block is evaluated in these four steps by the xOperator:
# (1) add the namespaces rdf: rdfs: owl: dc: and xop:
# (2) parse the content between <N3 and N3> to a memory model
# (3) use a construct query { ?s a xop:QueryScript. ?s ?p ?o } where ?s is set
#     to the registered script URL
# (4) write the resulting triples in the default graph of the users local store

# This means, you can configure special values in your N3 script which can be
# queried by the script and which can change the script behavior.

N3> The N3 documentation block ends here. Please leave this line untouched. */

/////////////////////////////////////////////
/// Implementation of "WHERE IS * NOW"
/////////////////////////////////////////////
context.startComposing()


//search for calendar documents

subject = context.getMatch(1);

calDocs = searchCalendar(subject);

switch (calDocs.size()){
	case 0:
		context.sendMessage("Sorry no calendars found for $subject.");
		break;
	default:
		context.sendMessage("Found ${calDocs.size()} calendars :  ${calDocs}") //
		calInf = queryCalendars(calDocs);
		printResults(calInf);
}

context.stopComposing();

def searchCalendar(of){
	def calDocs = [] as Set;
	query = 	"PREFIX ical: <http://www.w3.org/2002/12/cal/ical#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n " +
			"SELECT DISTINCT ?document "+
			"WHERE{?s ?p1 ?subjectpattern. ?s rdfs:seeAlso ?document.\n "+
			"?document rdf:type ical:Vcalendar.\n "+
			"FILTER regex(?subjectpattern, '.*"+of+".*', 'i').}"	
			
	context.queryForTable(query,true, null,null).each(){resultset->
		resultset.getResultRows().each(){resultrow->
				calDocs.add(resultrow["document"]);
		}
	}
	calDocs;
}



def queryCalendars(calDocs){

	now = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(new Date());
	
	whereQuery = "PREFIX ical: <http://www.w3.org/2002/12/cal/ical#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\n PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n " +
		"SELECT DISTINCT * \n";
//	calDocs.each{doc-> whereQuery += " FROM NAMED <$doc> "}
	whereQuery += "WHERE {" +
//		" GRAPH ?g { \n"+
		"?s ical:dtstart ?sbn. ?sbn ical:dateTime ?stime. \n"+
		"?s ical:dtend ?ebn. ?ebn ical:dateTime ?etime. \n"+
		"OPTIONAL {?s ical:location ?location.} \n"+
		"?s ical:summary ?summary. \n"+
		"FILTER (?stime < '"+now+"') \n"+
		"FILTER (?etime > '"+now+"') \n"+
//		"} OPTIONAL {?g rdfs:label ?graph}"  +
		"}"
	
	context.queryLocally(whereQuery)
}


def printResults(resultsets){

	i = 0;
	
	resultsets.each(){resultset->
			resultset.getResultRows().each(){ 
				context.sendMessageToUser((it["location"] !=null&&!it["location"].empty?it["location"]:"???" )+ " (doing: " + it["summary"] + ")")
				i++;
			}
	}
	
	if(i==0){
		context.sendMessage("Sorry, but there seems to be no entry for now");
	}
}
